/*!
 * 合成器
 * @author Sherlock
 * @date 2017年2月5日
 *--------------------------
 * hide方法  在合成器隐藏后触发
 * show方法  在合成器显示完成后触发
 */
require( './style.less' );

define( [
  'require',
  'jquery',
  'ajax',
  'api',
  'bigwe_utils',
  'bigwe_component',
  'message',
  'login',
  'constants',
  'bootstrap',
  'transit'
], function( require, $ ) {
  'use strict';
  var retParam = {};
  var c = require( 'constants' );
  var bc = require( 'bigwe_component' );
  var bu = require( 'bigwe_utils' );
  var apis = require( 'api' ).COMBINER;
  var login = require( 'login' );
  var _this = retParam.$selector = $( '.sidebar' );
  var news_all = new Array();
  var news_count = 0;
  var ShowTitleMessage = require( 'message' );
  var showTime = ShowTitleMessage.showTime;
  // 存在于loginmodule的回调函数的index
  var loginBackIndex = -1;
  // 获取合成器内容html
  var getHtml = function( article ) {
    var html = '';
    html += '<div data-articleID="' + article.cd + '">';
    html += '<div class="comb-detail-img" style="background-image: url(' + ( bu.wechartImgCheck( article.cover_img_url ) || c.resPath + '/images/wuyulantu.png' ) + ')"></div>';
    html += '<div class="comb-detail-title">' + ( article.title || '' ) + '</div>';
    // html += '<img class="comb-detail-img" src="' + bu.wechartImgCheck( article.cover_img_url ) + '" onerror="this.src=\'' + c.resPath + '/images/wuyulantu.png\';"/>';
    html += '<div class="comb-detail-filter">';
    html += '<button type="button" class="glyphicon glyphicon-eye-open" onclick="window.open(\'/article?p=' + article.cd + '\')"></button>';
    html += '<button type="button" class="glyphicon glyphicon-trash icon-delete" delete-event></button>';
    html += '</div>';
    html += '</div>';

    return html;
  }

  var refreshDom = function( articles ) {
    articles = articles || [];
    $( '.mer_num', _this ).html( articles.length || '' );

    if ( articles.length === 0 ) {
      $( ".side_con > p", _this ).show();
      $( '.side_con [data-articleid]', _this ).remove();
      return;
    }

    $( ".side_con > p", _this ).hide();

    var html = '';
    var article = null;
    for ( var i = 0; i < articles.length; i++ ) {

      article = articles[ i ];

      html += getHtml( article );
    }
    $( '.side_con [data-articleid]', _this ).remove();
    $( '.side_con', _this ).append( html );

    return html;
  }

  // 添加到购物车
  var addCar = function( startObj, fn ) {
    var $startObj = $( startObj );
    var $dataParent = $startObj.parent()

    var combination = {
      'title': $dataParent.attr( 'data-title' ),
      'image': $dataParent.attr( 'data-img' ),
      'cd': $dataParent.attr( 'data-articleID' ),
      'id': $dataParent.attr( 'data-id' ),
      'signature': $dataParent.attr( 'data-id' )
    };

    $( ".side_con > p", _this ).hide();
    if ( $startObj.hasClass( "check_box" ) ) {
      ShowTitleMessage.showWarning( "已经存在合成器啦！", showTime );
      return;
    }

    if ( $( '.side_con [data-articleid]', _this ).length === 8 ) {
      ShowTitleMessage.showWarning( "不能大于8篇文章！", showTime );
      return;
    }

    $startObj.addClass( "check_box" );

    if ( $( ".side_con div[data-articleid='" + combination[ 'cd' ] + "']", _this ).length != 0 ) {
      // ShowTitleMessage.showWarning( "已经存在合成器啦！", showTime );
      return;
    }

    var offset = $startObj.offset();
    var endOffset = $( ".merger", _this ).offset();
    $( "<span class='iconfont icon-box addshopcart'></span>" ).css( {
      top: offset.top,
      left: offset.left
    } ).appendTo( 'body' ).transit( {
      x: endOffset.left - offset.left,
      y: endOffset.top - offset.top + $( '.mer_mbar', _this ).outerHeight() / 2.4,
      scale: 0.5
    }, 400, 'out', function() {
      $( this ).remove();
    } );

    function addmatter() {
      news_count++;
      news_all.push( $( startObj ).parent().attr( 'data-articleID' ) );

      $( '.mer_num', _this ).text( news_count || '' );
    }

    // 添加一个图文到合成器
    _this.isAdding = true;
    return $.ajax( {
      type: 'post',
      url: apis.ADD,
      data: combination,
      success: function( data ) {
        data = typeof data === 'string' ? $.parseJSON( data ) : data;
        if ( data.ret == 0 ) {
          refreshDom( data.data.arts );
          if ( $.isFunction( fn ) ) {
            fn();
          }
        } else {
          ShowTitleMessage.showWarning( data.msg, ShowTitleMessage.showTime );
          if ( $( ".side_con div[data-articleid='" + combination[ 'cd' ] + "']", _this ).length == 0 ) {
            getMyArt();
          }
        }
      },
      complete: function() {
        _this.isAdding = false;
      }
    } );

  }
  var getMyArt = function() {
    return $.get( apis.GET_ART_LS, function( res ) {
      res = typeof res === 'string' ? $.parseJSON( res ) : res;
      news_count = res.data.total_number;

      var data = res.data.arts;
      refreshDom( data );
    } );
  }

  var loginCallback = function() {
    ShowTitleMessage.show( '正在获取合成器文章' );
    return getMyArt().then( function() {
      ShowTitleMessage.hide();
    } );
  };

  $( function() {
    // 已登录的状态加载图文
    if ( c.userLogin && $( '.side_btn .merger', _this ).length ) {
      getMyArt();
    } else { // 未登录的状态
      if ( $( '.side_btn .merger', _this ).length ) {
        loginBackIndex = login.addLoginCallback( loginCallback );
      }
    }
  } );

  // 动态取得header高度
  var headerHeight = $( '.header_container_main .top_main_nav' ).outerHeight();
  _this.css( {
    top: headerHeight
  } );

  $( document ).scroll( function() {
    var top = headerHeight - $( this ).scrollTop();
    top = top < 0 ? 0 : top;
    _this.css( {
      top: top
    } );
  } );

  /* sildebar */
  function moveOut() {
    _this.removeClass( 'active' );
    if ( $.isFunction( retParam.hide ) ) {
      clearTimeout( _this.timeId );
      _this.timeId = setTimeout( function() {
        retParam.hide.call( _this );
      }, 700 );
    }
  }
  _this.on( 'click', '.mer_mbar', function() {
      if ( _this.hasClass( 'active' ) ) {
        moveOut();
      } else {
        $( '.content_wrapper', _this ).removeClass( 'hide' )[ 0 ].clientWidth;
        _this.addClass( 'active' );
        if ( $.isFunction( retParam.show ) ) {
          clearTimeout( _this.timeId );
          _this.timeId = setTimeout( function() {
            retParam.show.call( _this );
          }, 700 );
        }
        $( document ).one( 'click.sidebar', moveOut );
      }

    } )
    .on( 'webkitTransitionEnd transitionend', '.content_wrapper', function( e ) {
      if ( e.target.id === 'content_wrapper' && !_this.hasClass( 'active' ) ) {
        $( this ).addClass( 'hide' );
      }
    } )
    // 删除图文
    .on( 'click', '[delete-event]', function() {
      var thisObj = $( this );
      bc.deleteConfirmShowBottom( {
        obj: this,
        fun: function() {
          thisObj.parent().parent().slideUp( function() {
            var articleId = $( this ).attr( 'data-articleID' );
            $.post( apis.DEL_ART, {
              'signature': articleId
            }, function( data ) {
              data = typeof data === 'string' ? $.parseJSON( data ) : data;
              if ( data.ret !== 0 ) {
                ShowTitleMessage.showWarning( data.msg, ShowTitleMessage.showTime );
              } else {
                refreshDom( data.data.arts );
              }
            } );
            $( this ).remove();

            $( '[addcar-event]' ).parent().each( function() {
              if ( $( this ).attr( 'data-articleid' ) === articleId ) {
                $( this ).find( '.check_box' ).removeClass( 'check_box' );
              }
            } );
            /*news_count--;
            if ( !news_count ) {
            	$( ".side_con > p", _this ).show();
            }
            $( '.mer_num', _this ).text( news_count || '' );
            $( this ).remove();*/
            //getMyArt();
          } );
        }
      } );
    } ).on( 'click', '.side_content>.btn_merge', function() {
      if ( $( '.side_con [data-articleid]', _this ).length === 0 ) {
        ShowTitleMessage.showWarning( '请先添加一篇文章', ShowTitleMessage.showTime );
        return;
      }
      if ( $( this ).text() === '正在生成中' ) return;
      var thisObj = $( this );
      thisObj.text( '正在生成中' );
      $.post( apis.MERGE, function( data ) {
        data = $.parseJSON( data );
        if ( data.ret != 0 ) {
          ShowTitleMessage.show( data.msg, ShowTitleMessage.showTime );
          return;
        } else {
          //ShowTitleMessage.show( '合成成功，请前往“<a href=\"/my_mpnews\" target=\"_blank\">我的图文</a>”中查看', ShowTitleMessage.showTime );
          if ( data.data && data.data.article_group ) {
            location.href = '/edit_text?article_group=' + data.data.article_group;
          }
          /*news_all = [];
          news_count = 0;
          $( '.side_con>div', _this ).fadeOut( function() {
            $( this ).remove();
            $( '.side_con>p' ).fadeIn();
          } );
          $( '.mer_num', _this ).text( news_count || '' );
          _this.removeClass( 'active' );*/
        }
      } ).then( function() {
        thisObj.text( '合并图文消息' );
      } );
      $( ".recom_build .icon-box, .add-merge, .article-merge,.compose" ).removeClass( "check_box" );
    } ).on( 'click', '.close.js_colse', moveOut );

  $( document ).on( 'click', '.delete_confirm,.sidebar', function( e ) {
    e.stopPropagation();
  } ).on( 'click', '[addCar-event]', function( e ) {
    var user_login = require( 'constants' ).userLogin;
    if ( user_login === '' ) {
      e.preventDefault();
      e.stopImmediatePropagation();
      login.$selector.modal( 'show' );
      login.loginCallback[ loginBackIndex ] && ( login.loginCallback[ loginBackIndex ] = $.proxy( function() {
        loginCallback().done( $.proxy( function() {
          ShowTitleMessage.hide();
          $( this ).trigger( 'click' );
        }, this ) );
      }, this ) );
    } else {
      if ( !_this.isAdding ) {
        addCar( this );
      } else {
        ShowTitleMessage.showWarning( '操作频率过快！', showTime );
      }
    }
  } );

  $( '.art_date', _this ).text( new Date().format( 'yyyy-MM-dd' ) );

  function phonePreviewAppend() {

    return [
      '<!DOCTYPE html><html>',
      '<head>',
      '<link rel="stylesheet" href="' + c.resPath + '/css/modules/simple_art_preview.css" />',
      '</head>',
      '<body>',
      '<div class="main_continer">',
      '<div class="art_head_info">',
      '<p class="article_title" setdata="title">输入你的文章标题</p>',
      '<p class="art_date_author">',
      '<span class="art_date article_meta_text">' + ( function( date ) {
        return date.getFullYear() + '-' + ( date.getMonth() + 1 ) + '-' + date.getDate();
      }( new Date() ) ) + '</span>',
      '<span class="art_author article_meta_text" id="art_author" setdata="author">作者</span>',
      '<span class="art_from article_meta_text" setdata="source">来源</span>',
      '</p>',
      '</div>',
      '<div id="art_preview_body" class="art_preview_body" setdata="content"></div>',
      '</div>',
      '</body></html>'
    ].join( '' );

  }

  // 手机预览
  var $iframe = null;
  if ( $( '.phone_preview', _this ).length ) {
    var iframe = document.createElement( 'iframe' );
    iframe.className = iframe.id = 'frame_preview_area';
    iframe.src = 'javascript: void(function(){document.open();document.write(\'' + phonePreviewAppend() + '\');document.close();}())';
    $( '.phone_preview .frame_container', _this ).append( iframe );

    $iframe = retParam.$iframe = $( '#frame_preview_area', _this ).contents();

  }
  retParam.setData = function( options ) {
    for ( var i in options ) {
      var value = options[ i ];
      $( '[setdata="' + i + '"]', $iframe ).text( value );
    }
  };

  ! function() {
    var beforeScrollTop = $( document ).scrollTop();
    // 小工具
    $( document ).on( {
      mouseenter: function() {
        $( this ).addClass( 'active' ).siblings().removeClass( 'active' );
        $( this ).parents( '.scan-wrapper' ).find( '.scan-content .scan-content-item' ).eq( $( this ).index() ).show().siblings().hide();
      },
      mouseleave: function() {

      }
    }, '.gadget .scan-wrapper .scan-tab-item' ).on( 'click', '.gadget .move-top', function() {
      $( 'html,body' ).animate( {
        scrollTop: 0
      } );
    } ).on( 'scroll', function( e ) {

      var afterScrollTop = $( document ).scrollTop(),
        delta = afterScrollTop - beforeScrollTop;
      if ( delta === 0 ) return false;
      beforeScrollTop = afterScrollTop;

      if ( $( this ).height() < $( window ).height() * 2 ) {
        if ( ( $( this ).height() - $( window ).height() - $( this ).scrollTop() ) < 1 ) {
          $( '.gadget .gadget-item', _this ).addClass( 'visibility-visible' );
          $( '.gadget', _this ).removeClass( 'bottom-trans' );
        } else {
          $( '.gadget', _this ).addClass( 'bottom-trans' );
          $( '.gadget .gadget-item', _this ).removeClass( 'visibility-visible' );
        }

      } else {
        if ( $( this ).scrollTop() > $( window ).height() ) {
          $( '.gadget .move-top', _this ).addClass( 'visibility-visible' );

          if ( delta > 0 ) {
            $( '.gadget .scan-joinus,.gadget .gadget-feedback', _this ).addClass( 'visibility-visible' );
            $( '.gadget', _this ).removeClass( 'bottom-trans' );
          } else {
            $( '.gadget', _this ).addClass( 'bottom-trans' );
            $( '.gadget .scan-joinus,.gadget .gadget-feedback', _this ).removeClass( 'visibility-visible' );
          }
        } else {
          $( '.gadget .move-top', _this ).removeClass( 'visibility-visible' );
        }
      }


      if ( c.pageID !== 'TLM016' ) {
        if ( $( this ).scrollTop() > $( '.header_container_main' ).outerHeight() ) {

          $( '.header_container_main' ).addClass( 'readyin' );
          if ( delta > 0 ) {
            $( '.header_container_main' ).removeClass( 'in' );
          } else {
            $( '.header_container_main' ).addClass( 'in' );
          }
        } else {
          $( '.header_container_main' ).addClass( 'in' );
        }
      }

    } );
  }();

  return retParam;
} );
